﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Bll;
using DevelopTool.Common;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.Enums;
using Sunny.UI;

namespace DevelopTool.Forms.CommonControls
{
    /// <summary>
    /// 管理页控件
    /// </summary>
    public partial class ManageControl : UIUserControl
    {

        #region 公有属性

        /// <summary>
        /// 节点名称
        /// </summary>
        private string _nodeText = "项";
        /// <summary>
        /// 节点名称
        /// </summary>
        [DefaultValue("项")]
        [Description("节点名称")]
        [Category("DevelopTool")]
        public string NodeText
        {
            get
            {
                return this._nodeText;
            }
            set
            {
                this._nodeText = value;
                SetContextMenuStripNodeText(value);
            }
        }


        /// <summary>
        /// 目录名称
        /// </summary>
        private string _folderText = "目录";
        /// <summary>
        /// 目录名称
        /// </summary>
        [DefaultValue("目录")]
        [Description("目录名称")]
        [Category("DevelopTool")]
        public string FolderText
        {
            get
            {
                return this._folderText;
            }
            set
            {
                this._folderText = value;
            }
        }

        /// <summary>
        /// 是否能新建节点
        /// </summary>
        private bool _isCanCreateNode = true;
        /// <summary>
        /// 是否能新建节点
        /// </summary>
        [DefaultValue(true)]
        [Description("是否能新建节点")]
        [Category("DevelopTool")]
        public bool IsCanCreateNode
        {
            get
            {
                return this._isCanCreateNode;
            }
            set
            {
                this._isCanCreateNode = value;
                this.新建项ToolStripMenuItem.Visible = value;
                this.新建项ToolStripMenuItem1.Visible = value;
                this.uiSymbolButton新建项.Enabled = value;
            }
        }

        /// <summary>
        /// 是否能新建目录
        /// </summary>
        private bool _isCanCreateFolder = true;
        /// <summary>
        /// 是否能新建目录
        /// </summary>
        [DefaultValue(true)]
        [Description("是否能新建目录")]
        [Category("DevelopTool")]
        public bool IsCanCreateFolder
        {
            get
            {
                return this._isCanCreateFolder;
            }
            set
            {
                this._isCanCreateFolder = value;
                this.新建目录ToolStripMenuItem.Visible = value;
                this.新建目录ToolStripMenuItem1.Visible = value;
                this.toolStripSeparator2.Visible = value;
                this.uiSymbolButton新建目录.Enabled = value;
            }
        }


        /// <summary>
        /// 是否能刷新
        /// </summary>
        private bool _isCanReload = true;
        /// <summary>
        /// 是否能刷新
        /// </summary>
        [DefaultValue(true)]
        [Description("是否能刷新")]
        [Category("DevelopTool")]
        public bool IsCanReload
        {
            get
            {
                return this._isCanReload;
            }
            set
            {
                this._isCanReload = value;
                this.uiSymbolButton刷新.Enabled = value;
            }
        }

        /// <summary>
        /// 是否允许修改节点名称
        /// </summary>
        private bool _isAllowModifyNodeName = true;
        /// <summary>
        /// 是否允许修改节点名称
        /// </summary>
        [DefaultValue(true)]
        [Description("是否允许修改节点名称")]
        [Category("DevelopTool")]
        public bool IsAllowModifyNodeName
        {
            get
            {
                return this._isAllowModifyNodeName;
            }
            set
            {
                this._isAllowModifyNodeName = value;
                this.重命名项ToolStripMenuItem.Visible = value;
                this.重命名目录ToolStripMenuItem.Visible = value;
                this.toolStripSeparator3.Visible = value;
                this.uiSymbolButton编辑.Enabled = value;
            }
        }


        /// <summary>
        /// 是否允许修改顶级节点名称
        /// </summary>
        private bool _isAllowModifyTopNodeName = true;
        /// <summary>
        /// 是否允许修改顶级节点名称
        /// </summary>
        [DefaultValue(true)]
        [Description("是否允许修改顶级节点名称")]
        [Category("DevelopTool")]
        public bool IsAllowModifyTopNodeName
        {
            get
            {
                return this._isAllowModifyTopNodeName;
            }
            set
            {
                this._isAllowModifyTopNodeName = value;
            }
        }

        /// <summary>
        /// 是否允许删除顶级节点
        /// </summary>
        private bool _isAllowDeleteTopNode = true;
        /// <summary>
        /// 是否允许删除顶级节点
        /// </summary>
        [DefaultValue(true)]
        [Description("是否允许删除顶级节点")]
        [Category("DevelopTool")]
        public bool IsAllowDeleteTopNode
        {
            get
            {
                return this._isAllowDeleteTopNode;
            }
            set
            {
                this._isAllowDeleteTopNode = value;
                this.删除项ToolStripMenuItem.Visible = value;
                this.删除目录ToolStripMenuItem.Visible = value;
                this.toolStripSeparator1.Visible = value;
                this.uiSymbolButton删除.Enabled = value;
            }
        }

        /// <summary>
        /// 是否显示操作栏
        /// </summary>
        private bool _isShowOperPanel = true;
        /// <summary>
        /// 是否显示操作栏
        /// </summary>
        [DefaultValue(true)]
        [Description("是否显示操作栏")]
        [Category("DevelopTool")]
        public bool IsShowOperPanel
        {
            get
            {
                return this._isShowOperPanel;
            }
            set
            {
                this._isShowOperPanel = value;
                this.pnlOper.Visible = value;
            }
        }

        /// <summary>
        /// 是否显示搜索框
        /// </summary>
        private bool _isShowSearchTextBox = true;
        /// <summary>
        /// 是否显示搜索框
        /// </summary>
        [DefaultValue(true)]
        [Description("是否显示搜索框")]
        [Category("DevelopTool")]
        public bool IsShowSearchTextBox
        {
            get
            {
                return this._isShowSearchTextBox;
            }
            set
            {
                this._isShowSearchTextBox = value;
                this.textBoxMenuSearch.Visible = value;
            }
        }

        /// <summary>
        /// 当前选择的节点
        /// </summary>
        public TreeNode SelectedTreeNode
        {
            get
            {
                return this.uiNavMenuLeft.SelectedNode;
            }
        }

        /// <summary>
        /// 当前选择的菜单对象
        /// </summary>
        public ManageMenu SelectedManageMenu
        {
            get
            {
                if(this.uiNavMenuLeft.SelectedNode != null && this.uiNavMenuLeft.SelectedNode.Tag != null && this.uiNavMenuLeft.SelectedNode.Tag is ManageMenu manageMenu)
                {
                    return manageMenu;
                }
                else
                {
                    return null;
                }
            }
        }


        /// <summary>
        /// 左侧菜单控件
        /// </summary>
        public UINavMenu NavMenuLeft
        {
            get
            {
                return this.uiNavMenuLeft;
            }
        }

        #endregion 公有属性

        #region 私有属性

        /// <summary>
        /// 菜单数据
        /// </summary>
        private List<ManageMenu> menuData;

        /// <summary>
        /// 搜索的菜单数据
        /// </summary>
        private Dictionary<string,List<ManageMenu>> menuQueryData;

        /// <summary>
        ///顶级节点，系统预定义
        /// </summary>
        private TreeNode topNode;

        /// <summary>
        /// 顶级节点文本
        /// </summary>
        private string _topTreeNodeText = "列表";

        /// <summary>
        /// 顶级节点图标
        /// </summary>
        private int _topTreeNodeSymbol = 61641;

        /// <summary>
        /// 是否展开菜单
        /// </summary>
        private bool doExpand = false;

        /// <summary>
        /// TreeView帮助类
        /// </summary>
        private TreeViewHelper treeViewHelper;

        /// <summary>
        /// 用于记录是否是搜索状态
        /// </summary>
        private bool firstSearch = false;

        public BaseBll BaseBll;


        private UIContextMenuStrip bindContextMenuStrip;

        #endregion 私有属性

        #region 事件
        //事件参数
        public delegate void OperationHandler(object sender,MenuEventArgs e);

        /// <summary>
        /// 新增菜单节点事件
        /// </summary>
        [Description("新增菜单节点事件"), Category("DevelopTool")]
        public event OperationHandler MenuAdd;

        /// <summary>
        /// 菜单节点名称重命名事件
        /// </summary>
        [Description("菜单节点名称重命名事件"), Category("DevelopTool")]
        public event OperationHandler MenuRename;

        /// <summary>
        /// 需要重新加载菜单数据事件
        /// </summary>
        [Description("需要重新加载菜单数据事件"), Category("DevelopTool")]
        public event EventHandler MenuNeedReLoad;

        /// <summary>
        /// 删除菜单节点事件
        /// </summary>
        [Description("删除菜单节点事件"), Category("DevelopTool")]
        public event OperationHandler MenuDelete;

        /// <summary>
        ///拖放菜单节点事件
        /// </summary>
        [Description("拖放菜单节点事件"), Category("DevelopTool")]
        public event OperationHandler MenuDrag;

        /// <summary>
        /// 单击菜单节点事件
        /// </summary>
        [Description("单击菜单节点事件"), Category("DevelopTool")]
        public event OperationHandler MenuClick;

        /// <summary>
        /// 双击菜单节点事件
        /// </summary>
        [Description("双击菜单节点事件"), Category("DevelopTool")]
        public event OperationHandler MenuDoubleClick;


        public delegate void QueryHandler(object sender,string text);
        /// <summary>
        /// 搜索菜单事件
        /// </summary>
        [Description("搜索菜单事件"), Category("DevelopTool")]
        public event QueryHandler MenuQuery;

        /// <summary>
        /// 在向菜单添加节点时的事件
        /// </summary>
        [Description("在向菜单添加节点时的事件"), Category("DevelopTool")]
        public event OperationHandler MenuAdded;

        #endregion 事件


        public ManageControl()
        {
            InitializeComponent();
        }

        private void ManageControl_Load(object sender,EventArgs e)
        {
            uiToolTip.SetToolTip(uiSymbolButton新建项,$"新建{this._nodeText}");
            uiToolTip.SetToolTip(uiSymbolButton新建目录,$"新建{this._folderText}");
            uiToolTip.SetToolTip(uiSymbolButton编辑,"重命名");
            uiToolTip.SetToolTip(uiSymbolButton刷新,"刷新");
            uiToolTip.SetToolTip(uiSymbolButton删除,"删除");

            this.uiSplitContainer.SplitterDistance = Setting.Theme.ManageControlLeftWidth(null,this.GetParentControl<Form>()?.GetType().FullName);
        }


        /// <summary>
        /// 设置右键菜单的节点文本
        /// </summary>
        /// <param name="text"></param>
        private void SetContextMenuStripNodeText(string text)
        {
            foreach(ToolStripItem toolStripItem in this.contextMenuStripNode.Items)
            {
                toolStripItem.Text = toolStripItem.Text.Replace("项",text);
            }

            foreach(ToolStripItem toolStripItem in this.contextMenuStripTopNode.Items)
            {
                toolStripItem.Text = toolStripItem.Text.Replace("项",text);
            }

            foreach(ToolStripItem toolStripItem in this.contextMenuStripFolder.Items)
            {
                toolStripItem.Text = toolStripItem.Text.Replace("项",text);
            }
        }

        #region 公有方法

        /// <summary>
        /// 设置菜单数据
        /// </summary>
        /// <param name="menuData"></param>
        public void SetMenuData(List<ManageMenu> menuData,string topTreeNodeText = "列表",int topTreeNodeSymbol = 61641)
        {
            this.menuData = menuData;
            this._topTreeNodeText = topTreeNodeText;
            this._topTreeNodeSymbol = topTreeNodeSymbol;
            LoadMenu();
        }


        /// <summary>
        /// 设置搜索的菜单数据
        /// </summary>
        /// <param name="menuQueryData"></param>
        public void SetMenuQueryData(Dictionary<string,List<ManageMenu>> menuQueryData)
        {
            this.menuQueryData = menuQueryData;
            LoadMenuQueryData();
        }


        /// <summary>
        /// 显示内容窗体
        /// </summary>
        /// <param name="code"></param>
        public void ShowPageForm(Control pageForm,string pageTitle,bool openOne = true,string pageFlag = "")
        {
            TabControlHelper.AddPageToTabControl(uiTabControlRight,pageForm,pageTitle,openOne,pageFlag);
        }

        /// <summary>
        /// 显示控件
        /// </summary>
        /// <param name="control"></param>
        public void ShowControl(Control control)
        {
            control.Dock = DockStyle.Fill;

            this.uiSplitContainer.Panel2.Controls.Clear();

            this.uiSplitContainer.Panel2.Controls.Add(control);
            ThemHelper.SetSystemThem(control);
        }


        /// <summary>
        /// 选中节点
        /// </summary>
        /// <param name="nodeText"></param>
        public void SelectNode(ManageMenu manageMenu)
        {
            TreeNode treeNode = TreeViewHelper.GetTreeNodeByText(this.uiNavMenuLeft,manageMenu.NodeName);
            if(treeNode != null)
            {
                this.uiNavMenuLeft.SelectedNode = treeNode;
                treeNode.Checked = true;
            }

        }

        /// <summary>
        /// 设置节点图标
        /// </summary>
        /// <param name="manageMenu"></param>
        /// <param name="symbol"></param>
        public void SetSymbol(ManageMenu manageMenu,int symbol)
        {
            TreeNode treeNode = TreeViewHelper.GetTreeNodeByText(this.uiNavMenuLeft,manageMenu.NodeName);
            if(treeNode != null)
            {
                this.uiNavMenuLeft.SetNodeSymbol(treeNode,symbol);
            }
        }

        #endregion


        /// <summary>
        /// 加载菜单
        /// </summary>
        private void LoadMenu()
        {
            this.uiNavMenuLeft.ClearAll();

            //创建顶级节点
            var topMenu = new ManageMenu() { Id = 0,NodeType = MenuNodeType.Folder };
            topNode = this.uiNavMenuLeft.CreateNode(this._topTreeNodeText,new Random().Next());
            topNode.Name = "TopNode";
            topNode.Tag = new ManageMenu() { Id = 0,NodeType = MenuNodeType.Folder };

            SetNodeDefaultSymbol(topNode);

            MenuAdded?.Invoke(this.uiNavMenuLeft,new MenuEventArgs() { ManageMenu = topMenu,TreeNode = topNode });

            LoadingHelper.ShowLoading("正在绑定菜单",() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    this.BindMenuData(topNode,this.menuData);
                }));

            });

            topNode.Expand();//绑定完节点后，展开菜单
        }


        /// <summary>
        /// 递归绑定菜单节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="menus"></param>
        public void BindMenuData(TreeNode parentNode,List<ManageMenu> menus)
        {
            var parentMenu = parentNode?.Tag as ManageMenu;
            var subMenus = menus.Where(menu => menu.NodePid == parentMenu?.Id).ToList();

            foreach(var menu in subMenus)
            {
                TreeNode newNode = CreateAndConfigureNode(parentNode,menu);
                BindMenuData(newNode,menus);
            }
        }

        private TreeNode CreateAndConfigureNode(TreeNode parentNode,ManageMenu menu)
        {
            TreeNode newNode;

            if(parentNode == null)
            {
                newNode = this.uiNavMenuLeft.CreateNode(menu.NodeName,menu.Id);
            }
            else
            {
                newNode = this.uiNavMenuLeft.CreateChildNode(parentNode,menu.NodeName,menu.Id);
            }

            switch(menu.NodeType)
            {
                case MenuNodeType.Folder:
                    newNode.Name = "Folder";
                    break;
                case MenuNodeType.Node:
                    newNode.Name = "Node";
                    break;
            }

            newNode.Tag = menu;
            newNode.ImageIndex = menu.Id;
            SetNodeDefaultSymbol(newNode);

            MenuAdded?.Invoke(this.uiNavMenuLeft,new MenuEventArgs { ManageMenu = menu,TreeNode = newNode });

            return newNode;
        }


        /// <summary>
        /// 根据节点类型设置默认的图标
        /// </summary>
        /// <param name="node"></param>
        /// <param name="isSetChildNodes">是否设置子节点的图标</param>
        private void SetNodeDefaultSymbol(TreeNode node,bool isSetChildNodes = false)
        {
            switch(node.Name)
            {
                case "TopNode"://顶级节点
                    this.uiNavMenuLeft.SetNodeSymbol(node,_topTreeNodeSymbol);
                    break;
                case "Folder"://目录节点
                    this.uiNavMenuLeft.SetNodeSymbol(node,61564);
                    break;
                case "Node"://子节点
                    this.uiNavMenuLeft.SetNodeSymbol(node,361788);
                    break;
                default:
                    this.uiNavMenuLeft.SetNodeSymbol(node,61462);
                    break;
            }

            if(isSetChildNodes)//递归设置子节点的图标
            {
                foreach(TreeNode treeNode in node.Nodes)
                {
                    SetNodeDefaultSymbol(treeNode,isSetChildNodes);
                }
            }
        }


        /// <summary>
        /// 左侧菜单的节点上鼠标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_NodeMouseClick(object sender,TreeNodeMouseClickEventArgs e)
        {
            ManageMenu menu = e.Node.Tag as ManageMenu;
            var args = new MenuEventArgs() { ManageMenu = menu,TreeNode = e.Node };
            MenuClick?.Invoke(e,args);
            if(args.Cancel) return;


            if(e.Button == MouseButtons.Right)//鼠标右键
            {
                switch(e.Node.Name)
                {
                    case "TopNode"://顶级节点
                        if(e.Node.ContextMenuStrip == null)//没有自定义菜单时，才绑定默认右键菜单
                            e.Node.ContextMenuStrip = contextMenuStripTopNode;
                        break;

                    case "Folder"://目录节点
                        if(e.Node.ContextMenuStrip == null)
                            e.Node.ContextMenuStrip = contextMenuStripFolder;
                        break;

                    case "Node"://子节点
                        if(e.Node.ContextMenuStrip == null)
                            e.Node.ContextMenuStrip = contextMenuStripNode;
                        break;
                }

            }
        }


        /// <summary>
        /// 双击菜单节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_NodeMouseDoubleClick(object sender,TreeNodeMouseClickEventArgs e)
        {
            if(e.Button == MouseButtons.Left)//鼠标左键
            {
                ManageMenu menu = e.Node.Tag as ManageMenu;

                //触发新建项事件
                var args = new MenuEventArgs() { ManageMenu = menu,TreeNode = e.Node };
                MenuDoubleClick?.Invoke(sender,args);
            }
        }





        /// <summary>
        /// 新建节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建项ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            CreateMenuItem(sender,MenuNodeType.Node);
        }

        /// <summary>
        /// 新建目录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建目录ToolStripMenuItem1_Click(object sender,EventArgs e)
        {
            CreateMenuItem(sender,MenuNodeType.Folder);
        }


        /// <summary>
        /// 新建菜单项
        /// </summary>
        /// <param name="nodeType"></param>
        private void CreateMenuItem(object sender,MenuNodeType nodeType)
        {
            TreeNode selectMenuNode = this.uiNavMenuLeft.SelectedNode ?? topNode;//当前选中的节点
            ManageMenu selectMenu = selectMenuNode.Tag as ManageMenu;//当前选中节点的Menu对象

            string menuName = "";//菜单名称
            string treeNodeName = "";//菜单控件节点名称
            switch(nodeType)
            {
                case MenuNodeType.Folder:
                    menuName = this._folderText + DateTime.Now.DateTimeString(false);
                    treeNodeName = "Folder";
                    break;
                case MenuNodeType.Node:
                    menuName = this._nodeText + DateTime.Now.DateTimeString(false);
                    treeNodeName = "Node";
                    break;
            }


            ManageMenu newMenu = new ManageMenu()
            {
                NodeName = menuName,
                NodeType = nodeType,
            };


            TreeNode parentNode;
            if(selectMenu.NodeType == MenuNodeType.Folder)//选中目录
            {
                newMenu.NodePid = selectMenu.Id;//设置父节点id
                parentNode = selectMenuNode;//父节点
            }
            else
            {//选中节点
                newMenu.NodePid = selectMenu.NodePid;
                parentNode = selectMenuNode.Parent;
            }

            //触发新建项事件
            var args = new MenuEventArgs() { ManageMenu = newMenu,TreeNode = null };
            MenuAdd?.Invoke(sender,args);
            if(args.Cancel) return;//取消操作
            newMenu = args.ManageMenu;


            TreeNode newTreeNode = uiNavMenuLeft.CreateChildNode(parentNode,newMenu.NodeName,new Random().Next());
            newTreeNode.Tag = newMenu;
            newTreeNode.Name = treeNodeName;

            SetNodeDefaultSymbol(newTreeNode);

            MenuAdded?.Invoke(this.uiNavMenuLeft,new MenuEventArgs() { ManageMenu = newMenu,TreeNode = newTreeNode });

            this.doExpand = false;

            parentNode.Expand();//展开父节点

            uiNavMenuLeft.SelectedNode = newTreeNode;//选中新建的节点

        }


        /// <summary>
        /// 清空搜索框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxMenuSearch_ButtonClick(object sender,EventArgs e)
        {
            this.textBoxMenuSearch.Text = string.Empty;
        }



        /// <summary>
        /// 搜索菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxMenuSearch_TextChanged(object sender,EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.textBoxMenuSearch.Text))
            {
                if(!this.firstSearch)
                {
                    this.firstSearch = true;
                    treeViewHelper = new TreeViewHelper();
                    treeViewHelper.ExecStoreNodeState(topNode);
                }
                MenuQuery?.Invoke(sender,textBoxMenuSearch.Text);
            }
            else
            {
                if(this.firstSearch)
                {
                    LoadMenu();
                    this.firstSearch = false;
                    treeViewHelper.SetTreeNodeState(topNode,this.uiNavMenuLeft);
                }
            }
        }


        /// <summary>
        /// 加载菜单搜索数据
        /// </summary>
        private void LoadMenuQueryData()
        {
            uiNavMenuLeft.ClearAll();

            foreach(var item in this.menuQueryData)
            {
                var topNode = uiNavMenuLeft.CreateNode(item.Key,new Random().Next());
                topNode.Name = "TopNode";
                topNode.Tag = new ManageMenu() { Id = 0,NodeType = MenuNodeType.Node };
                SetNodeDefaultSymbol(topNode);

                foreach(ManageMenu menu in item.Value)
                {
                    var newTreeNode = uiNavMenuLeft.CreateChildNode(topNode,menu.NodeName,new Random().Next());
                    newTreeNode.Tag = menu;
                    newTreeNode.Name = "Node";

                    SetNodeDefaultSymbol(newTreeNode);

                    MenuAdded?.Invoke(this.uiNavMenuLeft,new MenuEventArgs() { ManageMenu = menu,TreeNode = newTreeNode });
                }
                topNode.Expand();
            }
            this.uiNavMenuLeft.ExpandAll();
        }


        /// <summary>
        /// 菜单折叠前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_BeforeCollapse(object sender,TreeViewCancelEventArgs e)
        {

            if(e.Node.Name == "TopNode")//顶级节点不允许折叠
            {
                e.Cancel = true;
            }
            else
            {
                e.Cancel = this.doExpand;
            }
        }

        /// <summary>
        /// 菜单展开前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_BeforeExpand(object sender,TreeViewCancelEventArgs e)
        {
            e.Cancel = this.doExpand;
        }

        /// <summary>
        /// 点击菜单事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_MouseDown(object sender,MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {//鼠标右键
                this.doExpand = true;
            }
            else
            {
                this.doExpand = false;
            }
        }

        /// <summary>
        /// 编辑菜单名称事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButton编辑_Click(object sender,EventArgs e)
        {
            MenuNodeRename(sender);
        }


        /// <summary>
        /// 菜单名称重命名
        /// </summary>
        /// <param name="sender"></param>
        private void MenuNodeRename(object sender)
        {
            TreeNode currentSelectNode = this.uiNavMenuLeft.SelectedNode;//当前选中的节点
            if(currentSelectNode == null) return;

            if(!this._isAllowModifyNodeName && currentSelectNode.Name == "Node") return;//是否允许修改节点名称

            if(currentSelectNode.Name != "Folder" && currentSelectNode.Name != "Node") return;//只能修改目录或节点的名称

            ManageMenu manageMenu = currentSelectNode.Tag as ManageMenu;
            if(!this._isAllowModifyTopNodeName && manageMenu.NodePid == 0) return;//是否允许修改顶级节点名称

            string nodeName = currentSelectNode.Text;
            string lable = "";
            switch(currentSelectNode.Name)
            {
                case "Folder": lable = this._folderText; break;
                case "Node": lable = this._nodeText; break;
            }

            if(UIInputDialog.ShowInputStringDialog(ref nodeName,this.Style,true,$"请输入新的{lable}名称："))
            {
                manageMenu.NodeName = nodeName;

                //触发修改节点名称事件
                var args = new MenuEventArgs() { ManageMenu = manageMenu,TreeNode = currentSelectNode };
                MenuRename?.Invoke(sender,args);
                if(args.Cancel) return;

                //设置节点名称
                currentSelectNode.Tag = manageMenu;
                currentSelectNode.Text = nodeName;
            }
        }

        /// <summary>
        /// 刷新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButton刷新_Click(object sender,EventArgs e)
        {
            treeViewHelper = new TreeViewHelper();
            treeViewHelper.ExecStoreNodeState(topNode);
            MenuNeedReLoad?.Invoke(sender,e);
            LoadMenu();
            treeViewHelper.SetTreeNodeState(topNode,uiNavMenuLeft);

        }


        /// <summary>
        /// 删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButton删除_Click(object sender,EventArgs e)
        {
            TreeNode currentSelectNode = this.uiNavMenuLeft.SelectedNode;//当前选中的节点
            if(currentSelectNode == null) return;
            if(currentSelectNode.Name != "Folder" && currentSelectNode.Name != "Node") return;//只能删除目录或节点的名称


            ManageMenu manageMenu = currentSelectNode.Tag as ManageMenu;

            if(!this._isAllowDeleteTopNode && manageMenu.NodePid == 0) return;

            if(UIMessageBox.ShowMessageDialog($"是否确定删除【{currentSelectNode.Text}】","提示",true,UIStyle.Orange))
            {
                //触发删除节点事件
                var args = new MenuEventArgs() { ManageMenu = manageMenu,TreeNode = currentSelectNode };
                MenuDelete?.Invoke(sender,args);

                if(args.Cancel) return;

                currentSelectNode.Remove();

            }
        }


        /// <summary>
        /// 菜单项上按下某一按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_KeyDown(object sender,KeyEventArgs e)
        {
            if(e.KeyCode == Keys.F2)//F2事件
            {
                MenuNodeRename(sender);
            }
        }



        #region 菜单拖放操作

        /// <summary>
        /// 开始拖放事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_ItemDrag(object sender,ItemDragEventArgs e)
        {
            if(e.Item is TreeNode treeNode)
            {
                if(treeNode.Name == "Folder" || treeNode.Name == "Node")//只能拖动目录和节点
                {
                    DoDragDrop(e.Item,DragDropEffects.Move);//开始拖放操作
                }
            }
        }

        /// <summary>
        /// 确定移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_DragEnter(object sender,DragEventArgs e)
        {
            e.Effect = e.AllowedEffect;
        }


        /// <summary>
        /// 拖放完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiNavMenuLeft_DragDrop(object sender,DragEventArgs e)
        {
            TreeNode dragNode = null;//拖拽的对象

            if(e.Data.GetDataPresent(typeof(TreeNode)))
                dragNode = e.Data.GetData(typeof(TreeNode)) as TreeNode;

            Point point = uiNavMenuLeft.PointToClient(new Point(e.X,e.Y));//目标节点位置
            TreeNode targetNode = uiNavMenuLeft.GetNodeAt(point);//目标节点

            if(dragNode == null) return;
            if(targetNode == null) return;
            // if (targetNode.Name != "Folder") return;//只能移动到目录节点

            ManageMenu targetMenu = targetNode.Tag as ManageMenu;//目标目录
            ManageMenu dragMenu = dragNode.Tag as ManageMenu;//需要移动的节点

            if(dragMenu.Id == targetMenu.Id) return;//不能移动到自己身上

            dragMenu.NodePid = targetMenu.Id;

            //触发移动节点事件
            var args = new MenuEventArgs() { ManageMenu = dragMenu,TreeNode = dragNode };
            MenuDrag?.Invoke(sender,args);
            if(args.Cancel) return;

            //开始界面移动
            var node = dragNode.Clone() as TreeNode;
            node.Tag = dragMenu;
            targetNode.Nodes.Add(node);
            dragNode.Remove();//删除原节点

            SetNodeDefaultSymbol(node,true);

            MenuAdded?.Invoke(this.uiNavMenuLeft,new MenuEventArgs() { ManageMenu = dragMenu,TreeNode = node });

            targetNode.Expand();

        }

        #endregion


        #region TabControl 事件

        /// <summary>
        /// 添加TabPage页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTabControlRight_ControlAdded(object sender,ControlEventArgs e)
        {
            TabPage tabPage = e.Control as TabPage;
            uiTabControlRight.SelectTab(tabPage);//跳转到此tab窗口
        }


        /// <summary>
        /// 实现右键选中选项卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTabControlRight_MouseDown(object sender,MouseEventArgs e)
        {
            uiTabControlRight.ContextMenuStrip = null;

            if(e.Button == MouseButtons.Right)
            {
                for(int i = 0 ; i < uiTabControlRight.TabPages.Count ; i++)
                {
                    //计算TabPage标签的显示区域，并检查鼠标是否在当前TabPage的标签区域内
                    if(uiTabControlRight.GetTabRect(i).Contains(new Point(e.X,e.Y)))
                    {
                        TabPage tp = uiTabControlRight.TabPages[i];
                        uiTabControlRight.SelectedTab = tp;
                        break;
                    }
                }
                uiTabControlRight.ContextMenuStrip = contextMenuStripTopTab;  //绑定右键菜单
            }
        }


        /// <summary>
        /// 鼠标移过 TabPage的标签时，Tip显示截断的标题文字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTabControlRight_MouseMove(object sender,MouseEventArgs e)
        {
            for(int i = 0 ; i < uiTabControlRight.TabPages.Count ; i++)
            {
                //计算TabPage标签的显示区域，并检查鼠标是否在当前TabPage的标签区域内  
                if(uiTabControlRight.GetTabRect(i).Contains(new Point(e.X,e.Y)))
                {
                    if(uiTabControlRight.TabPages[i].Tag is Tuple<string,string> tagTuple)
                    {
                        uiToolTip2.SetToolTip(uiTabControlRight,tagTuple.Item1);
                    }
                    break;
                }
            }
        }


        private void uiTabControlRight_MouseLeave(object sender,EventArgs e)
        {
            uiTabControlRight.ContextMenuStrip = null;  //离开选项卡后 取消菜单
        }


        /// <summary>
        /// ContextMenuStripTopTab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关闭当前页ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            uiTabControlRight.SelectedTab.Dispose();  //关闭当前选中的tabpage页
        }


        /// <summary>
        /// ContextMenuStripTopTab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关闭所有页ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(UIMessageBox.ShowMessageDialog($"是否关闭所有窗口？","提示",true,UIStyle.Orange))
            {
                foreach(TabPage tp in uiTabControlRight.TabPages)
                {
                    tp.Dispose();   //关闭全部tabpage 页
                }
            }
        }


        /// <summary>
        /// ContextMenuStripTopTab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关闭非当前页ToolStripMenuItem_Click(object sender,EventArgs e)
        {

            if(UIMessageBox.ShowMessageDialog($"是否关闭非当前窗口？","提示",true,UIStyle.Orange))
            {
                foreach(TabPage tabPage in uiTabControlRight.TabPages)
                {
                    if(tabPage == uiTabControlRight.SelectedTab) continue;//跳过当前选项卡
                    tabPage.Dispose(); //关闭非当前tabpage 页
                }
            }
        }


        private bool uiTabControlRight_BeforeRemoveTabPage(object sender,int index)
        {
            UITabControl tabControl = sender as UITabControl;

            SystemMenuModel systemMenu = SystemMenu.GetMenuByText(tabControl.TabPages[index].Text,SystemMenu.List);

            //关闭前确认
            if(systemMenu != null && systemMenu.IsCloseConfirm)
            {
                if(new CountDownAskMessageForm($"{GlobalData.AppName_zh}-提示",$"请确认保存后再关闭窗口！",0,UIStyle.Inherited).ShowDialog() == DialogResult.OK)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        #endregion TabControl 事件        


        private void 属性ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            ManageMenu manageMenu = this.uiNavMenuLeft.SelectedNode.Tag as ManageMenu;

            ShowAttributeForm showAttributeForm = new ShowAttributeForm(manageMenu.Id);
            showAttributeForm.BaseBll = this.BaseBll;
            showAttributeForm.ShowDialog(this);
        }


        private void contextMenuStripTopNode_Opened(object sender,EventArgs e)
        {
            //隐藏属性菜单项
            if(sender is UIContextMenuStrip contextMenuStrip && BaseBll == null)
            {
                for(int i = 0 ; i < contextMenuStrip.Items.Count ; i++)
                {
                    ToolStripItem toolStripItem = contextMenuStrip.Items[i];

                    if(toolStripItem.Text == "属性")
                    {

                        toolStripItem.Visible = false;
                        toolStripSeparator5.Visible = false;
                        toolStripSeparator4.Visible = false;
                    }
                }
            }
        }


        private void contextMenuStripNode_Opening(object sender,CancelEventArgs e)
        {
            if(sender is UIContextMenuStrip contextMenuStrip && BaseBll == null)
            {
                if(!contextMenuStrip.Items.Cast<ToolStripItem>().Any(it => it.Visible))
                {
                    //  e.Cancel = true;
                }
            }
        }

        #region 外部右键菜单相关

        /// <summary>
        /// 绑定外部右键菜单 到 目录节点
        /// </summary>
        /// <param name="contextMenuStrip"></param>
        public void BindContextMenuStripToFolder(UIContextMenuStrip contextMenuStrip)
        {
            if(contextMenuStrip == null) return;

            this.bindContextMenuStrip = contextMenuStrip;

            for(int i = 0 ; i < contextMenuStrip.Items.Count ; i++)
            {
                ToolStripItem toolStripItem = contextMenuStrip.Items[i];

                if(toolStripItem is ToolStripMenuItem toolStrip)
                {
                    ToolStripMenuItem newToolStripMenuItem = new ToolStripMenuItem()
                    {
                        Name = toolStripItem.Name,
                        Text = toolStripItem.Text,
                    };
                    BindToolStripDropDownItems(toolStrip,newToolStripMenuItem);

                    newToolStripMenuItem.Click += this.NewToolStripMenuItem_Click;

                    this.contextMenuStripFolder.Items.Add(newToolStripMenuItem);
                }

                else if(toolStripItem.GetType().Equals(typeof(ToolStripSeparator)))
                {
                    this.contextMenuStripFolder.Items.Add(new ToolStripSeparator());
                }
            }
        }

        /// <summary>
        /// 绑定外部右键菜单 到 节点
        /// </summary>
        /// <param name="contextMenuStrip"></param>
        public void BindContextMenuStripToNode(UIContextMenuStrip contextMenuStrip)
        {
            if(contextMenuStrip == null) return;

            this.bindContextMenuStrip = contextMenuStrip;

            for(int i = 0 ; i < contextMenuStrip.Items.Count ; i++)
            {
                ToolStripItem toolStripItem = contextMenuStrip.Items[i];

                if(toolStripItem is ToolStripMenuItem toolStrip)
                {
                    ToolStripMenuItem newToolStripMenuItem = new ToolStripMenuItem()
                    {
                        Name = toolStripItem.Name,
                        Text = toolStripItem.Text,
                    };
                    BindToolStripDropDownItems(toolStrip,newToolStripMenuItem);

                    newToolStripMenuItem.Click += this.NewToolStripMenuItem_Click;

                    this.contextMenuStripNode.Items.Add(newToolStripMenuItem);
                }

                else if(toolStripItem.GetType().Equals(typeof(ToolStripSeparator)))
                {
                    this.contextMenuStripNode.Items.Add(new ToolStripSeparator());
                }
            }
        }

        /// <summary>
        /// 递归绑定外部右键菜单的子项
        /// </summary>
        /// <param name="toolStrip"></param>
        /// <param name="newToolStripMenuItem"></param>
        private void BindToolStripDropDownItems(ToolStripMenuItem toolStrip,ToolStripMenuItem newToolStripMenuItem)
        {
            foreach(ToolStripMenuItem item in toolStrip.DropDownItems)
            {
                ToolStripMenuItem newToolStripMenuItem2 = new ToolStripMenuItem()
                {
                    Name = item.Name,
                    Text = item.Text,
                };

                newToolStripMenuItem2.Click += this.NewToolStripMenuItem_Click;

                newToolStripMenuItem.DropDownItems.Add(newToolStripMenuItem2);

                if(item.HasDropDownItems)
                    BindToolStripDropDownItems(item,newToolStripMenuItem2);
            }
        }

        /// <summary>
        /// 外部右键菜单项的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(sender is ToolStripMenuItem toolStripItem)
            {
                if(this.bindContextMenuStrip == null) return;

                for(int i = 0 ; i < this.bindContextMenuStrip.Items.Count ; i++)
                {
                    ToolStripItem toolStrip = this.bindContextMenuStrip.Items[i];

                    if(toolStrip.Name == toolStripItem.Name && toolStrip.Text == toolStripItem.Text)
                    {
                        toolStrip.PerformClick();

                        break;
                    }
                    else if(toolStrip is ToolStripMenuItem menuItem)
                    {
                        ToolStripMenuItem subToolStripItem = GetSubToolStripItem(menuItem,toolStripItem.Name);
                        if(subToolStripItem != null)
                        {
                            subToolStripItem.PerformClick();
                            break;
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 按名称Name获取右键菜单的子项
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="childName"></param>
        /// <returns></returns>
        private ToolStripMenuItem GetSubToolStripItem(ToolStripMenuItem ctrl,string childName)
        {
            if(ctrl == null) return null;
            if(ctrl.Name == childName) return ctrl;

            if(ctrl.DropDownItems.Count == 0)
            {
                return null;
            }
            else
            {
                return (from ToolStripMenuItem subCtrl in ctrl.DropDownItems.Cast<ToolStripMenuItem>() select GetSubToolStripItem(subCtrl,childName)).FirstOrDefault(tb => tb != null);
            }
        }


        #endregion 外部右键菜单相关

        private void uiSplitContainer_SplitterMoved(object sender,SplitterEventArgs e)
        {
            Setting.Theme.ManageControlLeftWidth(e.SplitX,this.GetParentControl<Form>()?.GetType().FullName);
        }
    }

}
